package com.czhoujunlv.weather;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;

public class MainActivity extends AppCompatActivity {

    ViewPager viewPager;
    LinearLayout pointLayout;
    List<Fragment> fragments;
    List<String> cityList;
    List<ImageView> points;
    ImageView add,share;
    CityCodeManager codeManager = new CityCodeManager();
    String CityName;
    RefreshLayout refreshLayout;
    private cityFragmentAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        viewPager = findViewById(R.id.viewpager);
        pointLayout = findViewById(R.id.point);
        add = findViewById(R.id.city_add);
        fragments = new ArrayList<>();
        share = findViewById(R.id.share);
        refreshLayout =findViewById(R.id.refreshLayout);
        refreshLayout.setRefreshHeader(new ClassicsHeader(this));
        refreshLayout.setRefreshFooter(new ClassicsFooter(this));
        final Intent intent = getIntent();
        Thread thread = new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    DBmanage.initDB(MainActivity.this);//初始化数据库
                    String cityName = intent.getStringExtra("cityname");
                    //Log.i("添加城市名为null：",cityName);
//                    Codebean codebean = new Codebean();
//                    codebean.setCityCode(cityName);

                    if(cityName != null) {
                        Log.i("添加城市的名称",cityName);
                        CityName = codeManager.cityCodeMap.get(cityName);
                    }
                    if(CityName!=null)
                        Log.i("添加城市的邮编：",CityName);
                    cityList = DBmanage.queryAllCityName();
                    if(cityList.size()!=0 && CityName != null) {
                        cityList.add(CityName);
                    }
                } catch (Exception e) {
                    //Log.i("城市邮编：",CityName);
                    Log.i("异常：", e.toString());
                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            points = new ArrayList<>();
                            if(cityList.size()==0){
                                cityList.add("430104");//长沙
                                Log.i("有数据：",cityList.toString());
                                // cityList.add("511703");
                                //("110100");
                            }
                            refreshLayout.setOnRefreshListener(new OnRefreshListener() {
                                @Override
                                public void onRefresh(RefreshLayout refreshlayout) {
                                    refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
                                }
                            });
                            initPager();
                            adapter = new cityFragmentAdapter(getSupportFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, fragments);
                            viewPager.setAdapter(adapter);
                            initPoint();
                            viewPager.setCurrentItem(fragments.size()-1);
                            viewPager.clearOnPageChangeListeners();
                            viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                @Override
                                public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                                }

                                @Override
                                public void onPageSelected(int position) {
                                    for(int i=0;i<points.size();i++){
                                        points.get(i).setImageResource(R.drawable.unselect_point);
                                    }
                                    points.get(position).setImageResource(R.drawable.select_point);
                                }

                                @Override
                                public void onPageScrollStateChanged(int state) {

                                }
                            });

                            add.setOnClickListener(new View.OnClickListener() {//添加城市
                                @Override
                                public void onClick(View v) {
                                    Intent intent = new Intent(MainActivity.this,City_Manage.class);
                                    startActivity(intent);
                                    finish();
                                }
                            });
                            share.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
//                                    allShare();
//                                    share("天气预报");
                                    showShare();
                                    Toast.makeText(MainActivity.this,"点击分享",Toast.LENGTH_SHORT).show();
                                }
                            });
                        } catch (Exception e) {
                            Log.i("Mainactivity线程异常：", e.toString());
                        }
                    }
                });
            }
        };
        thread.start();
    }

    private void initPoint() {//初始化小圆点指示器
        for(int i =0 ;i<fragments.size();i++) {
            ImageView point = new ImageView(this);
            point.setImageResource(R.drawable.unselect_point);
            point.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) point.getLayoutParams();
            lp.setMargins(0,0,20,0);
            points.add(point);
            pointLayout.addView(point);
        }
        points.get(points.size()-1).setImageResource(R.drawable.select_point);
    }

    private void initPager() {
        for(int i =0 ; i <cityList.size();i++){//初始化城市的fragment
            cityWeatherFragment ctw = new cityWeatherFragment();
            Bundle bundle = new Bundle();
            bundle.putString("city",cityList.get(i));
            ctw.setArguments(bundle);
            fragments.add(ctw);
        }
    }

    /**
     * onekeyshare分享调用九宫格方法
     */
    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle("分享给你");
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://d.firim.top/4vef");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("这是一个APP");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://d.firim.top/4vef");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://d.firim.top/4vef");

        // 启动分享GUI
        oks.show(this);
    }

}